<template>
  <div class="timeline-view">
    <div class="timeline-header">
      <h2 class="timeline-title">
        <span class="timeline-icon">📅</span>
        数字遗迹时间线
      </h2>
      <div class="timeline-controls">
        <button
          class="timeline-sort-btn"
          @click="toggleSortOrder"
          :title="sortOrder === 'desc' ? '切换到升序' : '切换到降序'"
        >
          <span class="sort-icon">{{
            sortOrder === "desc" ? "⬇️" : "⬆️"
          }}</span>
          {{ sortOrder === "desc" ? "最新优先" : "最早优先" }}
        </button>
      </div>
    </div>

    <div class="timeline-container">
      <!-- 时间轴线 -->
      <div class="timeline-line"></div>

      <!-- 年份节点 -->
      <div
        v-for="([year, yearData]) in sortedTimelineData"
        :key="year"
        class="timeline-year"
        :class="{ 'is-current-year': isCurrentYear(year) }"
      >
        <!-- 年份标题 -->
        <div class="year-header">
          <div class="year-marker">
            <div class="year-dot"></div>
            <div class="year-pulse"></div>
          </div>
          <div class="year-info">
            <h3 class="year-title">{{ year }}年</h3>
            <div class="year-stats">
              <span class="year-count"
                >{{ (yearData.sites || []).length }}个网站倒闭</span
              >
              <span
                class="year-impact"
                :class="getImpactLevel(yearData?.sites?.length || 0)"
              >
                {{ getImpactText((yearData.sites || []).length) }}
              </span>
            </div>
          </div>
        </div>

        <!-- 网站列表 -->
        <div class="year-sites">
          <TransitionGroup name="site-fade" tag="div" class="sites-grid">
            <template
              v-for="(site, index) in yearData.sites || []"
              :key="site?.name || `site-${index}`"
            >
              <div
                v-if="site"
                class="timeline-site"
                @click="handleSiteClick(site)"
              >
                <div class="site-timeline-card">
                  <!-- 网站图标 -->
                  <div class="site-timeline-icon">
                    <img
                      v-if="getIconUrl(site.name)"
                      :src="getIconUrl(site.name)"
                      :alt="site.name"
                      @error="handleIconError"
                    />
                    <span v-else class="icon-fallback">
                      {{ getIconFallback(site.name) }}
                    </span>
                  </div>

                  <!-- 网站信息 -->
                  <div class="site-timeline-info">
                    <h4 class="site-timeline-name">{{ site.name }}</h4>
                    <div class="site-timeline-meta">
                      <span class="site-timeline-type">{{
                        getTypeLabel(site.type)
                      }}</span>
                      <span class="site-timeline-region">{{
                        getRegionLabel(site.region)
                      }}</span>
                    </div>
                    <p class="site-timeline-desc">{{ site.description }}</p>
                    <div class="site-timeline-date">
                      {{ formatDate(site.closureDate) }}
                    </div>
                  </div>

                  <!-- 悼念按钮 -->
                  <div class="site-timeline-actions">
                    <button
                      class="timeline-mourn-btn"
                      @click.stop="handleMourn(site)"
                      :class="{ 'is-mourned': isMourned(site.name) }"
                    >
                      🕯️
                    </button>
                  </div>
                </div>
              </div>
            </template>
          </TransitionGroup>
        </div>

        <!-- 年份分隔线 -->
        <div class="year-separator" v-if="!isLastYear(year)"></div>
      </div>

      <!-- 空状态 -->
      <div v-if="Object.keys(timelineData).length === 0" class="timeline-empty">
        <div class="empty-icon">📭</div>
        <div class="empty-text">暂无数据</div>
        <div class="empty-desc">没有找到符合条件的网站记录</div>
      </div>
    </div>

    <!-- 回到顶部按钮 -->
    <Transition name="fade">
      <button
        v-if="showBackToTop"
        class="back-to-top"
        @click="scrollToTop"
        title="回到顶部"
      >
        ⬆️
      </button>
    </Transition>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useCemeteryStore } from "@/stores/cemetery";
import iconMap from "@/assets/data/iconMap.json";
import { getTypeLabel, getRegionLabel, formatDate } from '@/utils/helpers';

const props = defineProps({
  sites: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["site-click", "mourn"]);

const store = useCemeteryStore();
const sortOrder = ref("desc"); // 'desc' | 'asc'
const showBackToTop = ref(false);
const mournedSites = ref(new Set());

// 计算属性
const timelineData = computed(() => {
  // 直接从store.deadSites过滤，避免循环依赖
  let sites =
    props.sites && props.sites.length > 0
      ? props.sites
      : store.deadSites.filter((site) => {
          // 应用搜索过滤
          const matchesSearch =
            !store.searchTerm ||
            site.name.toLowerCase().includes(store.searchTerm.toLowerCase()) ||
            site.description
              .toLowerCase()
              .includes(store.searchTerm.toLowerCase());

          // 应用类型过滤
          const matchesType =
            store.currentFilter === "all" || store.currentFilter === site.type;

          // 应用分类过滤
          const matchesCategory =
            store.currentCategory === "all" ||
            store.currentCategory === site.category;

          // 应用地区过滤
          const matchesRegion =
            store.currentRegion === "all" ||
            store.currentRegion === site.region;

          return (
            matchesSearch && matchesType && matchesCategory && matchesRegion
          );
        });

  const grouped = {};

  sites.forEach((site) => {
    if (site.year) {
      if (!grouped[site.year]) {
        grouped[site.year] = {
          year: site.year,
          sites: [],
        };
      }
      grouped[site.year].sites.push(site);
    }
  });

  // 按月份排序每年的网站
  Object.values(grouped).forEach((yearData) => {
    yearData.sites.sort((a, b) => {
      const dateA = new Date(a.closureDate || `${a.year}-12-31`);
      const dateB = new Date(b.closureDate || `${b.year}-12-31`);
      return dateB - dateA;
    });
  });

  return grouped || {};
});

const sortedTimelineData = computed(() => {
  if (!timelineData.value || typeof timelineData.value !== "object") {
    return [];
  }

  return Object.entries(timelineData.value).sort(([a], [b]) => {
    return sortOrder.value === "desc"
      ? Number(b) - Number(a)
      : Number(a) - Number(b);
  });
});

// 方法
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === "desc" ? "asc" : "desc";
};

const isCurrentYear = (year) => {
  return parseInt(year) === new Date().getFullYear();
};

const isLastYear = (year) => {
  const years = sortedTimelineData.value.map(([y]) => y);
  return year === years[years.length - 1];
};

const getImpactLevel = (count) => {
  if (count >= 10) return "high";
  if (count >= 5) return "medium";
  return "low";
};

const getImpactText = (count) => {
  if (count >= 10) return "重大损失";
  if (count >= 5) return "显著影响";
  return "轻微波动";
};

const getIconUrl = (siteName) => {
  return iconMap[siteName] || null;
};

const getIconFallback = (siteName) => {
  if (siteName) {
    const firstChar = siteName.charAt(0);
    return /[\u4e00-\u9fff]/.test(firstChar)
      ? firstChar
      : firstChar.toUpperCase();
  }
  return "🌐";
};

const handleIconError = (event) => {
  if (event?.target) {
    event.target.style.display = "none";
    if (event.target.nextElementSibling) {
      event.target.nextElementSibling.style.display = "flex";
    }
  }
};


const handleSiteClick = (site) => {
  emit("site-click", site);
};

const handleMourn = (site) => {
  mournedSites.value.add(site.name);

  // 保存到localStorage
  const mourned = Array.from(mournedSites.value);
  localStorage.setItem("mournedSites", JSON.stringify(mourned));

  emit("mourn", site);
};

const isMourned = (siteName) => {
  return mournedSites.value.has(siteName);
};

const scrollToTop = () => {
  window.scrollTo({
    top: 0,
    behavior: "smooth",
  });
};

const handleScroll = () => {
  showBackToTop.value = window.scrollY > 500;
};

// 生命周期
onMounted(() => {
  // 从localStorage加载悼念状态
  const mourned = JSON.parse(localStorage.getItem("mournedSites") || "[]");
  mournedSites.value = new Set(mourned);

  // 监听滚动事件
  window.addEventListener("scroll", handleScroll);
});

onUnmounted(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
.timeline-view {
  width: 100%;
  position: relative;
  margin-top: 2rem;
}

.timeline-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid var(--border-color);
}

.timeline-title {
  display: flex;
  align-items: center;
  margin: 0;
  font-size: 1.8rem;
  font-weight: 700;
  color: var(--text-primary);
}

.timeline-icon {
  margin-right: 0.75rem;
  font-size: 2rem;
}

.timeline-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.timeline-sort-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 0.5rem 1rem;
  color: var(--text-secondary);
  font-size: 0.9rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.timeline-sort-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: var(--accent-color);
  color: var(--text-primary);
}

.sort-icon {
  font-size: 1rem;
}

.timeline-view-toggle {
  display: flex;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  overflow: hidden;
}



/* 时间轴容器 */
.timeline-container {
  position: relative;
  padding-left: 3rem;
}

.timeline-line {
  position: absolute;
  left: 1.5rem;
  top: 0;
  bottom: 0;
  width: 2px;
  background: linear-gradient(
    to bottom,
    var(--accent-color) 0%,
    var(--secondary-color) 50%,
    var(--border-color) 100%
  );
}

/* 年份节点 */
.timeline-year {
  position: relative;
  margin-bottom: 3rem;
}

.timeline-year.is-current-year .year-marker .year-dot {
  background: var(--accent-color);
  box-shadow: 0 0 20px var(--accent-color);
  animation: pulse 2s infinite;
}

.year-header {
  display: flex;
  align-items: center;
  margin-bottom: 1.5rem;
}

.year-marker {
  position: absolute;
  left: -1.5rem;
  top: 0.5rem;
  display: flex;
  align-items: center;
  justify-content: center;
  transform: translateX(-50%);
}

.year-dot {
  width: 16px;
  height: 16px;
  background: var(--border-color);
  border: 3px solid var(--bg-primary);
  border-radius: 50%;
  transition: all 0.3s ease;
  z-index: 2;
}

.year-pulse {
  position: absolute;
  width: 24px;
  height: 24px;
  border: 2px solid var(--accent-color);
  border-radius: 50%;
  opacity: 0;
  animation: pulse-ring 2s infinite;
}

.year-info {
  margin-left: 1rem;
}

.year-title {
  font-size: 1.5rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 0.25rem 0;
}

.year-stats {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.year-count {
  color: var(--text-secondary);
  font-size: 0.9rem;
}

.year-impact {
  font-size: 0.8rem;
  font-weight: 500;
  padding: 0.2rem 0.5rem;
  border-radius: 12px;
}

.year-impact.high {
  background: rgba(255, 99, 99, 0.2);
  color: #ff6363;
}

.year-impact.medium {
  background: rgba(255, 193, 7, 0.2);
  color: #ffc107;
}

.year-impact.low {
  background: rgba(76, 175, 80, 0.2);
  color: #4caf50;
}

/* 网站列表 */
.year-sites {
  margin-left: 1rem;
}

.sites-grid {
  display: grid;
  gap: 1rem;
}

/* 网格布局样式 */
.sites-grid {
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
}

/* 网站卡片 */
.timeline-site {
  cursor: pointer;
}

.site-timeline-card {
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid var(--border-color);
  border-radius: 12px;
  padding: 1rem;
  transition: all 0.3s ease;
  display: flex;
  align-items: flex-start;
  gap: 1rem;
}

.site-timeline-card:hover {
  background: rgba(255, 255, 255, 0.08);
  border-color: var(--accent-color);
  transform: translateX(4px);
}

.site-timeline-icon {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  flex-shrink: 0;
}

.site-timeline-icon img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.icon-fallback {
  font-size: 1.2rem;
  font-weight: bold;
  color: var(--text-primary);
}

.site-timeline-info {
  flex: 1;
  min-width: 0;
}

.site-timeline-name {
  font-size: 1.1rem;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 0.25rem 0;
}

.site-timeline-meta {
  display: flex;
  gap: 0.75rem;
  margin-bottom: 0.5rem;
}

.site-timeline-type,
.site-timeline-region {
  font-size: 0.8rem;
  color: var(--text-secondary);
  background: rgba(255, 255, 255, 0.1);
  padding: 0.2rem 0.5rem;
  border-radius: 8px;
}

.site-timeline-desc {
  color: var(--text-secondary);
  font-size: 0.9rem;
  line-height: 1.4;
  margin: 0 0 0.5rem 0;
  display: -webkit-box;
  line-clamp: 2;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}



.site-timeline-date {
  color: var(--accent-color);
  font-size: 0.85rem;
  font-weight: 500;
}

.site-timeline-actions {
  display: flex;
  align-items: center;
}

.timeline-mourn-btn {
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 0.5rem;
  color: var(--text-secondary);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 1rem;
}

.timeline-mourn-btn:hover {
  background: rgba(255, 255, 255, 0.15);
  border-color: var(--accent-color);
}

.timeline-mourn-btn.is-mourned {
  background: var(--accent-color);
  border-color: var(--accent-color);
  color: white;
}

/* 年份分隔线 */
.year-separator {
  height: 1px;
  background: linear-gradient(
    90deg,
    transparent,
    var(--border-color),
    transparent
  );
  margin: 2rem 0;
}

/* 空状态 */
.timeline-empty {
  text-align: center;
  padding: 4rem 2rem;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 1rem;
  opacity: 0.5;
}

.empty-text {
  font-size: 1.2rem;
  font-weight: 600;
  margin-bottom: 0.5rem;
}

.empty-desc {
  font-size: 0.9rem;
  opacity: 0.8;
}

/* 回到顶部按钮 */
.back-to-top {
  position: fixed;
  bottom: 2rem;
  right: 2rem;
  width: 48px;
  height: 48px;
  background: var(--accent-color);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 1.2rem;
  cursor: pointer;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
  z-index: 1000;
}

.back-to-top:hover {
  background: var(--secondary-color);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.4);
}

/* 动画 */
@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.1);
    opacity: 0.8;
  }
}

@keyframes pulse-ring {
  0% {
    transform: scale(0.8);
    opacity: 1;
  }
  100% {
    transform: scale(2);
    opacity: 0;
  }
}

/* 过渡动画 */
.site-fade-enter-active,
.site-fade-leave-active {
  transition: all 0.3s ease;
}

.site-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.site-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .timeline-header {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }

  .timeline-controls {
    justify-content: space-between;
  }

  .timeline-container {
    padding-left: 2rem;
  }

  .timeline-line {
    left: 1rem;
  }

  .year-marker {
    left: -1rem;
    transform: translateX(-50%);
  }

  .year-info {
    margin-left: 0.5rem;
  }

  .year-title {
    font-size: 1.3rem;
  }

  .year-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }

  .sites-grid {
    grid-template-columns: 1fr !important;
  }

  .site-timeline-card {
    padding: 0.75rem;
  }

  .back-to-top {
    bottom: 1rem;
    right: 1rem;
    width: 40px;
    height: 40px;
    font-size: 1rem;
  }
}

@media (max-width: 480px) {
  .timeline-title {
    font-size: 1.5rem;
  }

  .timeline-controls {
    flex-direction: column;
    gap: 0.75rem;
  }

  .timeline-sort-btn {
    width: 100%;
    justify-content: center;
  }

  .site-timeline-card {
    flex-direction: column;
    text-align: center;
  }

  .site-timeline-icon {
    align-self: center;
  }

  .site-timeline-meta {
    justify-content: center;
  }
}
</style>
